package com.example.chatapp11


import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message as OsMessage
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.chatapp11.databinding.ActivityMainBinding


class MainActivity : AppCompatActivity() {
 lateinit var binding: ActivityMainBinding
 lateinit var mainhander: Handler
 lateinit var serverIp: String
 var serverPort: Int = 20000
 lateinit var userNickname: String
 private lateinit var messageAdapter: MessageAdapter
 private val messageList = ArrayList<com.example.chatapp11.Message>()
 private lateinit var socketThread: SocketThread

 override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  mainhander= object : Handler() {
   override fun handleMessage(msg: OsMessage) {
    //super.handleMessage(msg)
    if (msg.what==2) {
     // 检查是否是用户自己发送的消息（通过检查消息内容是否以用户昵称开头）
     val messageContent = msg.obj.toString()
     val isUserMessage = messageContent.startsWith("[$userNickname]")
     messageAdapter.addMessage(com.example.chatapp11.Message(messageContent, isUserMessage))
     // 滚动到底部
     binding.rvMessages.scrollToPosition(messageList.size - 1)
    }
   }
  }
  binding= ActivityMainBinding.inflate(layoutInflater)
  setContentView(binding.root)

  // 初始化RecyclerView
  messageAdapter = MessageAdapter(messageList)
  binding.rvMessages.adapter = messageAdapter
  binding.rvMessages.layoutManager = LinearLayoutManager(this)

  // 获取从ConnectActivity传递过来的IP、端口和昵称
  serverIp = intent.getStringExtra("SERVER_IP") ?: "10.120.16.167"
  serverPort = intent.getIntExtra("SERVER_PORT", 20000)
  userNickname = intent.getStringExtra("USER_NICKNAME") ?: "匿名用户"

  // 添加连接信息作为系统消息
  messageAdapter.addMessage(com.example.chatapp11.Message("正在连接到: $serverIp:$serverPort"))
  messageAdapter.addMessage(com.example.chatapp11.Message("您的昵称: $userNickname"))
  
  //连接 Socket 服务器
  socketThread=SocketThread(mainhander, serverIp, serverPort, userNickname)
  socketThread.start()
  binding.btnSend.setOnClickListener {
   val sendinfo=binding.etSendinfo.text.toString()
   if (sendinfo.isNotEmpty()) {
    //把 UI 线程的消息发送给非 UI 线程
    val msg=OsMessage()
    msg.what=1
    msg.obj="[$userNickname]: $sendinfo"
    SocketThread.revhandler.sendMessage(msg)
    // 清空输入框
    binding.etSendinfo.text.clear()
   }
  }

  // 退出按钮点击事件
  binding.btnExit.setOnClickListener {
   // 关闭Socket连接
   socketThread.interrupt()
   // 返回连接界面
   startActivity(Intent(this, ConnectActivity::class.java))
   finish()
  }
 }
}